import { ref, watch } from 'vue'

import { deptApi } from '@/apis'
import { TableRefHook } from '@/hooks'

type Params = {
  tableRefHook: TableRefHook
}

export function useDept({ tableRefHook }: Params) {
  const deptTree = ref([] as ITreeNode[])
  const selectedKeys = ref('')
  const treeLoading = ref(false)
  const searchValue = ref('')

  async function getDeptTree() {
    treeLoading.value = true

    deptTree.value = await deptApi.getDeptTree()

    treeLoading.value = false
  }

  function handleSelect(keys: any[]) {
    selectedKeys.value = keys[0]
    tableRefHook.refresh()
  }

  function handleSearch(value: string) {}

  watch(deptTree, val => {
    handleSearch('')
  })

  watch(searchValue, val => {
    handleSearch(val)
  })

  return {
    deptTree,
    selectedKeys,
    treeLoading,
    searchValue,
    getDeptTree,
    handleSelect
  }
}
